package com.intretech.umsin.auth.service;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.intretech.umsin.auth.vo.SysLogininforVo;
import com.intretech.umsin.common.constant.CacheConstants;
import com.intretech.umsin.common.constant.CommonConstant;
import com.intretech.umsin.common.exception.BusinessException;
import com.intretech.umsin.common.utils.MessageUtils;
import com.intretech.umsin.common.utils.ServletUtils;
import com.intretech.umsin.common.utils.StringUtils;
import com.intretech.umsin.redis.utils.RedisUtils;
import com.intretech.umsin.security.satoken.enums.DeviceType;
import com.intretech.umsin.security.satoken.enums.LoginType;
import com.intretech.umsin.security.satoken.model.AppletLoginUser;
import com.intretech.umsin.security.satoken.model.LoginUser;
import com.intretech.umsin.security.satoken.utils.LoginHelper;
import org.omg.CORBA.UserException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.function.Supplier;

/**
 * @version V1.0
 * @ClassName: SysLoginService
 * @Description: 功能描述 登录校验功能
 * @author: 李启联
 * @date: 2022-8-10 8:01
 * @Copyright: Copyright (c) 2022
 */
@Service
public class SysLoginService {

    //@Autowired
    //private SystemFeign systemFeign;
    @Autowired
    private AuthService authService;

    @Autowired
    private SysLogininforService sysLogininforService;


    /**
     * 登录
     */
    public String login(String username, String password) {
        LoginUser userInfo = authService.getUserInfo(username);

        checkLogin(LoginType.PASSWORD, username, () -> !BCrypt.checkpw(password, userInfo.getPassword()));
        // 获取登录token
        LoginHelper.loginByDevice(userInfo, DeviceType.PC);

        recordLogininfor(username, CommonConstant.LOGIN_SUCCESS, MessageUtils.message("user.login.success"));
        return StpUtil.getTokenValue();
    }

    /**
     * 手机短信登录
     * @param phonenumber
     * @param smsCode
     * @return
     */
    public String smsLogin(String phonenumber, String smsCode) {
        // 通过手机号查找用户
        LoginUser userInfo = authService.getUserInfoByPhonenumber(phonenumber);

        checkLogin(LoginType.SMS, userInfo.getUsername(), () -> !validateSmsCode(phonenumber, smsCode));
        // 生成token
        LoginHelper.loginByDevice(userInfo, DeviceType.APP);

        recordLogininfor(userInfo.getUsername(), CommonConstant.LOGIN_SUCCESS, MessageUtils.message("user.login.success"));
        return StpUtil.getTokenValue();
    }

    public String appletLogin(String xcxCode) {
        // xcxCode 为 小程序调用 wx.login 授权后获取
        // todo 自行实现 校验 appid + appsrcret + xcxCode 调用登录凭证校验接口 获取 session_key 与 openid
        String openid = "";
        AppletLoginUser userInfo = authService.getUserInfoByOpenid(openid);
        // 生成token
        LoginHelper.loginByDevice(userInfo, DeviceType.APPLET);

        recordLogininfor(userInfo.getUsername(), CommonConstant.LOGIN_SUCCESS, MessageUtils.message("user.login.success"));
        return StpUtil.getTokenValue();
    }

    /**
     * 退出登录
     */
    public void logout() {
        try {
            String username = LoginHelper.getUsername();
            StpUtil.logout();
            recordLogininfor(username, CommonConstant.LOGOUT, MessageUtils.message("user.logout.success"));
        } catch (NotLoginException e) {
        }
    }

    /**
     * 校验短信验证码
     */
    private boolean validateSmsCode(String phonenumber, String smsCode) {
        String code = RedisUtils.getCacheObject(CommonConstant.CAPTCHA_CODE_KEY + phonenumber);
        if (StringUtils.isBlank(code)) {
            recordLogininfor(phonenumber, CommonConstant.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire"));
            throw new BusinessException("验证码失效");
        }
        return code.equals(smsCode);
    }

    /**
     * 登录校验
     */
    private void checkLogin(LoginType loginType, String username, Supplier<Boolean> supplier) {
        String errorKey = CacheConstants.LOGIN_ERROR + username;
        Integer errorLimitTime = CacheConstants.LOGIN_ERROR_LIMIT_TIME;
        Integer setErrorNumber = CacheConstants.LOGIN_ERROR_NUMBER;
        String loginFail = CommonConstant.LOGIN_FAIL;

        // 获取用户登录错误次数(可自定义限制策略 例如: key + username + ip)
        Integer errorNumber = RedisUtils.getCacheObject(errorKey);
        // 锁定时间内登录 则踢出
        if (ObjectUtil.isNotNull(errorNumber) && errorNumber.equals(setErrorNumber)) {
            recordLogininfor(username, loginFail, MessageUtils.message(loginType.getRetryLimitExceed(), errorLimitTime));
            throw new BusinessException("登录重试超出限制");
        }

        if (supplier.get()) {
            // 是否第一次
            errorNumber = ObjectUtil.isNull(errorNumber) ? 1 : errorNumber + 1;
            // 达到规定错误次数 则锁定登录
            if (errorNumber.equals(setErrorNumber)) {
                RedisUtils.setCacheObject(errorKey, errorNumber, Duration.ofMinutes(errorLimitTime));
                //recordLogininfor(username, loginFail, MessageUtils.message(loginType.getRetryLimitExceed(), errorLimitTime));
                //throw new UserException(loginType.getRetryLimitExceed(), errorLimitTime);
            } else {
                // 未达到规定错误次数 则递增
                RedisUtils.setCacheObject(errorKey, errorNumber);
                //recordLogininfor(username, loginFail, MessageUtils.message(loginType.getRetryLimitCount(), errorNumber));
                //throw new UserException(loginType.getRetryLimitCount(), errorNumber);
            }
        }
        // 登录成功 清空错误次数
        RedisUtils.deleteObject(errorKey);
    }


    /**
     * 记录登录信息
     *
     * @param username 用户名
     * @param status   状态
     * @param message  消息内容
     * @return
     */
    public void recordLogininfor(String username, String status, String message) {
        SysLogininforVo logininfor = new SysLogininforVo();
        logininfor.setUserName(username);
        logininfor.setIpaddr(ServletUtils.getClientIP());
        logininfor.setMsg(message);
        logininfor.setAccessTime(LocalDateTime.now());
        // 日志状态
        if (StringUtils.equalsAny(status, CommonConstant.LOGIN_SUCCESS, CommonConstant.LOGOUT, CommonConstant.REGISTER)) {
            logininfor.setStatus(CommonConstant.LOGIN_SUCCESS_STATUS);
        } else if (CommonConstant.LOGIN_FAIL.equals(status)) {
            logininfor.setStatus(CommonConstant.LOGIN_FAIL_STATUS);
        }
        sysLogininforService.add(logininfor);
    }
}